﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace RTMBindings.Responses
{
    public static class RTMResponseFactory
    {
        public static RTMResponse ParseResponse<T>(string response) where T : RTMResponse
        {
            var reader = new StringReader(response);
            var xmlReader = XmlReader.Create(reader);
            var serializer = new XmlSerializer(typeof(T));
            var errorSerializer = new XmlSerializer(typeof (RTMFailResponse));
            var res = (RTMResponse)serializer.Deserialize(xmlReader);

            if (res.Status == RTMResponseStatus.Fail)
            {
                reader = new StringReader(response);
                xmlReader = XmlReader.Create(reader);
                res = errorSerializer.Deserialize(xmlReader) as RTMFailResponse;
            }

            return res;
        }
    }
}
